package com.netty.demo.heartbeat;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


public class HeartbeatClient {
	
	private Bootstrap bootstrap;
    private ChannelFutureListener channelFutureListener = null;
	
	private String ip;
	private int port;
	
	public HeartbeatClient(String ip,int port){
		this.ip = ip;
		this.port = port;
	}
	
	public void start(){
		bootstrap = new Bootstrap();
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			bootstrap.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress(new InetSocketAddress(ip, port))
				.handler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						// 創建分隔符緩沖對象
		                ByteBuf delimiter = Unpooled.copiedBuffer("www"
		                        .getBytes());
		                // 當達到最大長度仍沒找到分隔符 就拋出異常
		                ch.pipeline().addLast(
		                        new DelimiterBasedFrameDecoder(10000, true, false, delimiter));
		                // 將消息轉化成字符串對象 下面的到的消息就不用轉化了
		                //解碼
		                ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
		                ch.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
		                ch.pipeline().addLast(new HeartbeatClientHandler());					
					}
				});
			
			channelFutureListener = new ChannelFutureListener() {
				public void operationComplete(ChannelFuture f) throws Exception {
	                if (f.isSuccess()) {
	                    System.out.println("重新连接服务器成功");

	                } else {
	                	System.out.println("重新连接服务器失败");
	                    //  3秒後重新連接
	                    f.channel().eventLoop().schedule(new Runnable() {
	                        public void run() {
	                            doConnect();
	                        }
	                    }, 3, TimeUnit.SECONDS);
	                }
	            }
	        };
		} finally {
			group.shutdownGracefully();
		}
	}
	
//  連接到服務端
    public void doConnect() {
        System.out.println("doConnect");
        ChannelFuture future = null;
        try {
            future = bootstrap.connect(new InetSocketAddress(
                    ip, port));
            future.addListener(channelFutureListener);

        } catch (Exception e) {
            e.printStackTrace();
            //future.addListener(channelFutureListener);
        }
    }
    
    public static void main(String[] args) {
		new HeartbeatClient("127.0.0.1", 8007).start();;
	}
}
